//
//  UITextView+Extension.swift
//  表情键盘
//
//  Created by iOS on 16/9/29.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

extension UITextView {
    
    /// 获取表情名称字符串
    func emoticonNameText() -> String {
        var text: String = ""
        let range = NSRange(location: 0, length: attributedText.length)
        attributedText.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            // 每次遍历到一段内容就会调用一次, 可以根据范围截取需要字符串,如果是图片,在dict中会包含 NSAttachment 这个key
            //            print("遍历到了内容: range:\(range.location) - \(range.length), dict: \(dict)")
            
            if let attachment = dict["NSAttachment"] as? HMTextAttachment {
                // 图片表情
                text += attachment.chs ?? "找不到表情"
            } else {
                // 普通文本或emoji表情,截取文本
                let str = (attributedText.string as NSString).substring(with: range)
                
                text += str
            }
        }
        
        return text
    }
    
    
    /// 添加一个表情到TextView中
    ///
    /// - parameter emoitcon: 表情模型
    func insertEmoticon(emoticon: HMEmoticonModel) {

        // emoji表情
        if let emoji = emoticon.emoji {
            // 将emoji(文本)添加到textView中
            insertText(emoji)
            return
        }
        
        // 图片表情
        if let fullPngPath = emoticon.fullPngPath {
            let attributeText = emoticon.toAttributedText(font: font!)
            
            // 3.1获取当前textView中的属性文本
            let currentAttributeText = NSMutableAttributedString(attributedString: attributedText)
            // 3.2获取当前选中的范围
            let currentSelectedRange = selectedRange
            // 3.3当图片的属性文本添加到现有的属性文本中
            currentAttributeText.replaceCharacters(in: currentSelectedRange, with: attributeText)
            
            // 4.让textView显示属性文本
            attributedText = currentAttributeText
            // 5.重新设置光标位置
            let newSelectedRange = NSRange(location: currentSelectedRange.location + 1, length: 0)
            selectedRange = newSelectedRange
            
            // 添加表情键盘不会触发文字改变事件
            // 自己来触发
            NotificationCenter.default.post(name: .UITextViewTextDidChange, object: self)
            self.delegate?.textViewDidChange?(self)
        }
    }
}
